package com.rcadmin.busi.logview.service;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.util.StringUtils;

import com.rcadmin.busi.logview.ddl.ProjectDO;
import com.rcadmin.busi.logview.ddl.ResourceDO;
import com.rcadmin.common.bean.TreeObject;
import com.rcadmin.common.prop.LogViewProp;

/**
 * 
 * @author tanson lam
 * @create 2016年9月7日
 */
public class LogPathUtil {

	@Resource
	private static LogViewProp logViewProp;

	/**
	 * 加载项目在本地某的日志目录树
	 * 
	 * @param prefixName
	 * @param rootFile
	 * @param parentId
	 * @param fileTreeList
	 * @param deep
	 * @throws IOException
	 */
	public static void loadFileTree(String prefixName, File rootFile,
			String parentId, List<TreeObject> fileTreeList, int deep)
			throws IOException {
		loadFileTree(logViewProp.getDir(), prefixName, rootFile, parentId,
				fileTreeList, deep);
	}

	/**
	 * 加载项目在本地某的日志目录树
	 * 
	 * @param rootPath
	 * @param prefixName
	 * @param rootFile
	 * @param parentId
	 * @param fileTreeList
	 * @param deep
	 * @throws IOException
	 */
	public static void loadFileTree(String rootPath, String prefixName,
			File rootFile, String parentId, List<TreeObject> fileTreeList,
			int deep) throws IOException {
		if (!rootFile.isDirectory())
			throw new IOException("rootFile is not a directory."
					+ rootFile.getAbsolutePath());
		Integer index = 0;
		String prefixId = prefixName + "_" + deep;
		File[] files = rootFile.listFiles();
		for (File file : files) {
			String pId = prefixId + "_" + (++index);
			TreeObject treeNode = new TreeObject(pId, parentId, file.getName(),
					true, file.getAbsolutePath());
			if (file.isDirectory()) {
				loadFileTree(rootPath, prefixName, file, pId, fileTreeList,
						++deep);
			}
			fileTreeList.add(treeNode);
		}
	}

	/**
	 * 组装本地日志路径
	 * 
	 * @param project
	 * @param resource
	 * @param logFilePath
	 * @return
	 */
	public static String wrapLocalLogFilePath(ProjectDO project,
			ResourceDO resource, String logFilePath) {
		if (project == null || StringUtils.isEmpty(project.getLogDir()))
			throw new IllegalArgumentException("项目信息或日志目录不能为空！");
		if (resource == null || StringUtils.isEmpty(resource.getServerAddr()))
			throw new IllegalArgumentException("资源信息或资源地址不能为空！");
		if (StringUtils.isEmpty(logFilePath))
			throw new IllegalArgumentException("日志地址不能为空！");
		logFilePath = logFilePath.replace(project.getLogDir(), "");
		StringBuffer sb = new StringBuffer();
		// sb.append(busiProperties).append(File.separator);
		sb.append(resource.getServerAddr()).append(File.separator);
		sb.append(project.getLogDir()).append(File.separator);
		sb.append(logFilePath);
		return sb.toString();
	}
}
